var express = require('express');
var router = express.Router();

/* GET home page. */
var path=require("path");
var fs=require("fs");
var fpath=path.join(__filename,"..","Data.json");
var Data=require(fpath);



function store(){
  fs.writeFile(fpath,JSON.stringify(Data),function (error){});
}

router.get('/', function(req, res,) {
  var User=req.session.User || "";
  var Message=Data.Message;
  res.render('index', {User,Message});
});


router.post("/reg",function (req,res){
  var {userName,passWord,confirm}=req.body;
  if(userName && passWord === confirm && Data.User.userName == undefined){
      Data.User[userName] = {userName,passWord};
      store();
  }
  res.redirect("back");
});

router.post("/login",function (req,res){
  var {userName,passWord}=req.body;
  if(userName && Data.User[userName].passWord === passWord){
    req.session.User = userName;
  }
  res.redirect("back");
});

module.exports = router;
